package com.bailian.system.utils;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JSON对象数组解析工具类
 * 
 * @author bailian
 */
public class JsonObjectArrayParser {
    
    private static final Logger log = LoggerFactory.getLogger(JsonObjectArrayParser.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 解析JSON字符串为ID列表
     * 支持两种格式：
     * 1. 简单数组：[1, 2, 3]
     * 2. 对象数组：[{"typeId": 1, ...}, {"typeId": 2, ...}]
     * 
     * @param jsonString JSON字符串
     * @return ID列表
     */
    public static List<Long> parseToIdList(String jsonString) {
        if (jsonString == null || jsonString.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        try {
            // 首先尝试解析为简单的Long数组 [1, 2, 3]
            return objectMapper.readValue(jsonString, new TypeReference<List<Long>>() {});
        } catch (Exception e1) {
            try {
                // 如果失败，尝试解析为对象数组，提取typeId字段
                List<Map<String, Object>> objectList = objectMapper.readValue(jsonString, new TypeReference<List<Map<String, Object>>>() {});
                List<Long> typeIds = new ArrayList<>();
                for (Map<String, Object> obj : objectList) {
                    if (obj.containsKey("typeId") && obj.get("typeId") != null) {
                        Object typeIdObj = obj.get("typeId");
                        if (typeIdObj instanceof Number) {
                            typeIds.add(((Number) typeIdObj).longValue());
                        } else if (typeIdObj instanceof String) {
                            typeIds.add(Long.parseLong((String) typeIdObj));
                        }
                    }
                }
                return typeIds;
            } catch (Exception e2) {
                log.warn("Failed to parse JSON to ID list: {}, Error1: {}, Error2: {}", jsonString, e1.getMessage(), e2.getMessage());
                return new ArrayList<>();
            }
        }
    }
}
